#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<unordered_set>
using namespace std;


struct ListNode{
    int val;
    ListNode* next;
    ListNode(int x): val(x), next(nullptr){}
};

class Solution{
    public:

    ListNode* ans1(ListNode* head, int k){
        ListNode* temp = head;
        if(!head){
            return head;
        }
        int len = 1;
        while(temp->next){
            temp = temp->next;
            len++;
        }
        temp->next = head;
        ListNode* ret = temp->next;
        int index = len - k % len;
        for(int i = 0; i != index-1; i++){
            ret = ret->next;
        }
        ListNode* ans = ret->next;
        ret->next = nullptr;
        return ans;
    }

};

void test1(){
    vector<int> num = {1,2,3,4,5};
    ListNode* head = nullptr;
    ListNode* tail = nullptr;
    for(int i = 0; i != num.size(); i++){
        if(!head){
            head = tail = new ListNode(num[i]);
        }else{
            tail->next = new ListNode(num[i]);
            tail = tail->next;
        }
    }
    int k = 2;

    Solution s;
    ListNode* ret = s.ans1(head, k);
    while(ret){
        cout << ret->val << " " << ends;
        ret = ret->next;
    }
    cout << endl;
}

void test2(){
    vector<int> num = {0,1,2};
    ListNode* head = nullptr;
    ListNode* tail = nullptr;
    for(int i = 0; i != num.size(); i++){
        if(!head){
            head = tail = new ListNode(num[i]);
        }else{
            tail->next = new ListNode(num[i]);
            tail = tail->next;
        }
    }
    int k = 4;

    Solution s;
    ListNode* ret = s.ans1(head, k);
    while(ret){
        cout << ret->val << " " << ends;
        ret = ret->next;
    }
    cout << endl;
}


int main(void){
    test1();
    test2();

    return 0;
}